<template>
  <div class="transfer-records">
    <div class="record-header">
      <div class="tab-container">
        <div class="tab-item left" :class="{ active: recordStatus == '0' }" @click="handleStatusChange('0')">
          上传中（{{ recordCount.progress }}）
        </div>
        <div class="tab-item right" :class="{ active: recordStatus == '0' }" @click="handleStatusChange('1')">
          已上传（{{ recordCount.finished }}）
        </div>
      </div>
      <div class="action-buttons">
        <el-button class="batch-btn batch-start" size="small" @click="startAllUploads" :disabled="!hasCheckedItems">
          批量开始
        </el-button>
        <el-button class="batch-btn batch-pause" size="small" @click="pauseAllUploads" :disabled="!hasProgressUploads">
          批量暂停
        </el-button>
        <el-button class="batch-btn batch-cancel" size="small" @click="cancelSelectedUploads"
          :disabled="!hasCheckedItems">
          批量取消
        </el-button>
      </div>
    </div>

    <el-table v-loading="loading" :data="uploadRecords" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="文件名称" min-width="200">
        <template #default="scope">
          <div class="file-name-cell">
            <el-icon v-if="scope.row.fileType === 'folder'">
              <Folder />
            </el-icon>
            <el-icon v-else-if="scope.row.fileType === 'image'">
              <Picture/>
            </el-icon>
            <el-icon v-else-if="scope.row.fileType === 'video'">
              <VideoPlay />
            </el-icon>
            <el-icon v-else-if="scope.row.fileType === 'audio'">
              <Headset />
            </el-icon>
            <el-icon v-else>
              <Document />
            </el-icon>
            <span>{{ scope.row.fileName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" width="100">
        <template #default="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="上传时间" width="160" />
      <el-table-column label="上传状态" width="180">
        <template #default="scope">
          <div v-if="recordStatus == '0'">
            <el-progress :percentage="scope.row.progress" :color="customColor" />
          </div>
          <span v-else-if="recordStatus == '1'" class="success-status">已完成</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <template v-if="recordStatus === '0'">
            <el-button v-if="scope.row.isPause == '0'" link type="warning" size="small"
              @click="pauseUploadFn(scope.row)">暂停</el-button>
            <el-button v-if="scope.row.isPause == '1'" link type="primary" size="small"
              @click="resumeUploadFn(scope.row)">继续</el-button>
            <el-button  link type="danger"
              size="small" @click="cancelUploadFn(scope.row)">取消</el-button>
          </template>
          <template v-else-if="recordStatus === '1'">
            <!-- <el-button link type="primary" size="small">查看</el-button> -->
            <el-button link type="danger" size="small" @click="deleteRecord(scope.row)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
        layout="total, prev, pager, next, jumper" :total="pagination.total" @current-change="handleCurrentChange" />
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import message from '~/utils/message'
import { pauseUpload, resumeUpload, cancelUpload } from '~/api/netdisk/file'
import { Document, Folder, Picture, VideoPlay, Headset } from '@element-plus/icons-vue'
import { pageNetdiskRecord, uploadProgress,countNetdiskRecord } from '@/api/netdisk/record'

// 记录筛选
const recordStatus = ref('0')
const progressTimer = ref(null)
const loading = ref(false)
const selectedRows = ref([])
// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})
// 上传记录数据
const uploadRecords = ref([])
// 计算上传中和已上传的数量
const recordCount = ref({
  progress: 0,
  finished: 0
})
const customColor = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 },
]
// 计算属性：是否有正在上传的文件
const hasProgressUploads = computed(() => {
  return uploadRecords.value.some(record => record.fileStatus == '0')
})

// 计算属性：是否有选中的项目
const hasCheckedItems = computed(() => {
  return selectedRows.value.length > 0
})

// 处理选择变更
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}
const initLoading = async () => {
  loading.value = true
  await loadUploadRecords()
  await getUploadProgress()
  loading.value = false
}

// 获取上传记录数量
const getRecordCount = async ()=>{
  const res =await countNetdiskRecord({recordType:"upload"})
  if (res.code == 200) {
    recordCount.value=res.data;
  } else {
    message.error("获取上传文件数量失败")
  }
}

// 获取上传记录列表
const loadUploadRecords = async () => {
  const params = {
    recordType: 'upload',
    recordStatus: recordStatus.value,
    size: pagination.size,
    current: pagination.current
  }
  const res = await pageNetdiskRecord(params)
  if (res.code === 200) {
    uploadRecords.value = res.data.records
    pagination.total = res.data.total
    clearInterval(progressTimer.value)
    if (recordStatus.value == '0' && pagination.total > 0) {
      progressTimer.value = setInterval(() => {
        getUploadProgress()
      }, 1500)
    }
  } else {
    message.error('获取上传记录失败')
  }
}
// 获取上传进度
const getUploadProgress = async () => {
  const res = await uploadProgress()
  if (res.code == 200) {
    uploadRecords.value.map(item => {
      const progress = Math.floor(res.data[item.recordId])  
      if (progress) {
        item.progress = progress;
      }else{
        item.recordStatus="1"
      }
    })
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 KB';
  const units = ['KB', 'MB', 'GB', 'TB'];
  let index = 0;
  let formattedSize = size;
  while (formattedSize >= 1024 && index < units.length - 1) {
    formattedSize /= 1024;
    index++;
  }
  return `${formattedSize.toFixed(2)} ${units[index]}`;
}


const handleCurrentChange = (current) => {
  pagination.current = current
  initLoading()
}

// 状态切换
const handleStatusChange = (status) => {
  recordStatus.value = status
  pagination.current = 1
  initLoading()
}

// 暂停单个上传
const pauseUploadFn = async (record) => {
  try {
    await pauseUpload({ recordId: record.recordId })
    message.success(`已暂停上传: ${record.fileName}`)
    uploadRecords.value.map(item => {
      if (item.recordId == record.recordId) {
        item.isPause = '1'
      }
    })
  } catch (error) {
    message.error('暂停上传失败')
  }
}
// 继续单个上传
const resumeUploadFn = async (record) => {
  try {
    await resumeUpload({ recordId: record.recordId })
    message.success(`已继续上传: ${record.fileName}`)
    uploadRecords.value.map(item => {
      if (item.recordId == record.recordId) {
        item.isPause = '0'
      }
    })
  } catch (error) {
    message.error('继续上传失败')
  }
}
// 取消单个上传
const cancelUploadFn = (record) => {
  ElMessageBox.confirm(`确定要取消 ${record.fileName} 的上传吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await cancelUpload({ recordId: record.recordId })
    if (res.code == 200) {
      message.success(`已取消上传: ${record.fileName}`)
      loadUploadRecords()
    } else {
      message.error(res.message || '取消上传失败')
    }
  })
}
// 批量取消选中的上传
const cancelSelectedUploads = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要取消的上传任务')
    return
  }

  ElMessageBox.confirm(`确定要取消选中的 ${selectedRows.value.length} 个上传任务吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应该调用批量取消API
    // cancelUploadFiles({ fileIds: selectedRows.value.map(row => row.recordId) })
    message.success(`已取消 ${selectedRows.value.length} 个上传任务`)
    loadUploadRecords()
  }).catch(() => { })
}

// 全部开始上传
const startAllUploads = async () => {
  try {
    // 实际项目中应该调用批量开始API
    // await startAllUploadFiles()
    message.success('已开始所有上传')
    loadUploadRecords()
  } catch (error) {
    message.error('开始所有上传失败')
  }
}

// 暂停所有上传
const pauseAllUploads = async () => {
  try {
    // 实际项目中应该调用批量暂停API
    // await pauseAllUploadFiles()
    message.success('已暂停所有上传')
    loadUploadRecords()
  } catch (error) {
    message.error('暂停所有上传失败')
  }
}


// 删除记录
const deleteRecord = (record) => {
  ElMessageBox.confirm(`确定要删除 ${record.fileName} 的上传记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应该调用删除API
    // deleteUploadRecord({ recordId: record.recordId })
    message.success('删除成功')
    loadUploadRecords()
  }).catch(() => { })
}

// 页面加载时获取数据
onMounted(async () => {
  getRecordCount()
  await initLoading()
})
// 销毁
onBeforeUnmount(() => {
  clearInterval(progressTimer.value)
})
</script>

<style scoped>
.transfer-records {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.record-header {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 15px;
}

.record-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.left-section {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
  gap: 15px;
}

.tab-container {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  width: 280px;
  position: relative;
}

.tab-item {
  position: relative;
  padding: 8px 15px;
  cursor: pointer;
  text-align: center;
  flex: 1;
  background-color: #fff;
  color: #888;
  transition: all 0.3s;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e0e0e0;
}

.tab-item.left {
  border-radius: 6px 0 0 6px;
  border-right: none;
}

.tab-item.right {
  border-radius: 0 6px 6px 0;
}

.tab-item.active {
  color: #6c9efc;
  border-color: #6c9efc;
  z-index: 1;
}

/* 当左侧激活时，确保右侧标签页的左边框为蓝色 */
.tab-item.left.active+.tab-item.right {
  border-left-color: #6c9efc;
}

/* 当右侧激活时，确保左侧标签页的右边框为蓝色 */
.tab-item.right.active {
  border-left-color: #6c9efc;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 8px;
}

.batch-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 16px;
  border-radius: 4px;
  font-weight: normal;
  font-size: 14px;
  transition: all 0.2s;
  border: none;
}

.batch-start {
  background-color: #6c9efc;
  color: white;
}

.batch-start:hover:not(:disabled) {
  background-color: #5a8ae6;
}

.batch-pause {
  background-color: #f0ad4e;
  color: white;
}

.batch-pause:hover:not(:disabled) {
  background-color: #ec971f;
}

.batch-cancel {
  background-color: #f77b7b;
  color: white;
}

.batch-cancel:hover:not(:disabled) {
  background-color: #f55a5a;
}

.batch-btn i {
  margin-right: 4px;
  font-size: 14px;
}

.file-name-cell {
  display: flex;
  align-items: center;
}

.file-name-cell span {
  margin-left: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-info {
  color: #606266;
  font-size: 14px;
}

.page-goto {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  font-size: 14px;
}

.page-goto .el-input {
  width: 50px;
  margin: 0 5px;
}

@media screen and (max-width: 768px) {
  .record-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .tab-container,
  .action-buttons {
    width: 100%;
  }

  .action-buttons {
    justify-content: space-between;
  }

  .pagination-container {
    flex-direction: column;
    align-items: center;
    gap: 10px;
  }
}

.success-status {
  color: #67c23a;
  font-weight: 500;
}
</style>